package com.hph.health.controller;

import cn.hutool.core.io.FileUtil;
import com.hph.health.common.BaseResponse;
import com.hph.health.common.ErrorCode;
import com.hph.health.common.ResultUtils;
import com.hph.health.constant.FileConstant;
import com.hph.health.exception.BusinessException;
import com.hph.health.exception.ThrowUtils;
import com.hph.health.mapper.SocialShareMapper;
import com.hph.health.model.dto.file.UploadFileRequest;
import com.hph.health.model.entity.Product;
import com.hph.health.model.entity.ProductPicInfo;
import com.hph.health.model.entity.SocialShare;
import com.hph.health.model.entity.User;
import com.hph.health.service.ProductPicInfoService;
import com.hph.health.service.ProductService;
import com.hph.health.service.SocialShareService;
import com.hph.health.service.UserService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

/**
 * 文件接口
 *
 * @author hanph
 * @from haut
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    private UserService userService;
    @Resource
    private ProductService productService;

    @Resource
    private ProductPicInfoService productPicInfoService;

    @Resource
    private SocialShareService socialShareService;
    /**
     * 文件上传
     *
     * @param multipartFile
     */
    @PostMapping("/upload")
    public BaseResponse<String> uploadFile( @RequestPart("file") MultipartFile multipartFile,
                                            UploadFileRequest uploadFileRequest) {
        if (multipartFile.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
        }
        String fileAdress = "";
        String fileEnd = "";
        String URL = "";
        String type = uploadFileRequest.getType();
        Long id = uploadFileRequest.getId();
        validFile(multipartFile);
        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        if (type.equals("user")){
            fileAdress =FileConstant.USER_FILE;
            fileEnd =FileConstant.USER_END_FILE;
            URL  =fileEnd + fileName;
            User user = new User();
            user.setId(id);
            user.setUserAvatar(URL);
            boolean result = userService.updateById(user);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        }else if (type.equals("product")){
            fileAdress =FileConstant.PRODUCT_FILE;
            fileEnd =FileConstant.PRODUCT_END_FILE;
            URL  =fileEnd + fileName;
            Product product = new Product();
            product.setId(id);
            product.setPicUrl(URL);
            boolean result = productService.updateById(product);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        } else if (type.equals("proPic")) {
            fileAdress =FileConstant.PRODUCT_FILE;
            fileEnd =FileConstant.PRODUCT_END_FILE;
            URL  =fileEnd + fileName;
            ProductPicInfo productPicInfo = new ProductPicInfo();
            productPicInfo.setProductId(id);
            productPicInfo.setPicUrl(URL);
            productPicInfo.setPicDesc(id+"的图片");
            productPicInfo.setPicDesc("1");
            productPicInfo.setPicOrder(1);
            productPicInfo.setIsMaster(1);
            boolean result = productPicInfoService.save(productPicInfo);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        }else if (type.equals("share")) {
            fileAdress =FileConstant.PRODUCT_FILE;
            fileEnd =FileConstant.PRODUCT_END_FILE;
            URL  =fileEnd + fileName;

            SocialShare socialShare = new SocialShare();
            socialShare.setId(id);
            socialShare.setShareAvatar(URL);
            boolean result = socialShareService.updateById(socialShare);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        }
        try {
            // 指定存储目录
            String filePath = fileAdress + fileName;
            // 创建目录
            File dest = new File(filePath);
            dest.getParentFile().mkdirs();
            // 写入文件
            FileOutputStream fos = new FileOutputStream(dest);
            fos.write(multipartFile.getBytes());
            fos.close();
            return ResultUtils.success("上传成功");
        } catch (IOException e) {
            new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
        }
        return ResultUtils.success("上传成功");
    }

    /**
     * 校验文件
     *
     * @param multipartFile
     */
    private void validFile(MultipartFile multipartFile) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long ONE_M = 2048 * 1024L;
            if (fileSize > ONE_M) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 2M");
            }
            if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
    }
}
